<template>
  <div v-cloak>
    <!-- 主体内容 -->
    <div class="main-content">
      <h2 class="section-title">文件信息</h2>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
            v-model="name"
            placeholder="请输入文件名称"
            style="width: 200px; margin-right: 10px"
        />
        <el-select v-model="typeId" placeholder="请选择文件类型" style="width: 200px; margin-right: 10px">
          <el-option :value="0" label="所有类型" />
          <el-option
              v-for="item in typeObjs"
              :key="item.id"
              :value="item.id"
              :label="item.name"
          />
        </el-select>
        <el-button type="primary" @click="loadTable(1)">搜索</el-button>
        <el-button type="success" @click="add" v-permission="[1]">新增</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%" class="data-table">
        <el-table-column prop="name" label="文件名称" />
        <el-table-column prop="time" label="上传时间" />
        <el-table-column prop="typeName" label="分类名称" />
        <el-table-column prop="userName" label="上传人" />
        <el-table-column label="文件操作">
          <template #default="{ row }">
            <el-button size="small" @click="viewModal(row)">预览</el-button>
            <el-button type="success" size="small" @click="downFile(row.id)">下载</el-button>
          </template>
        </el-table-column>
        <el-table-column label="记录操作">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="init(row)" v-permission="[3]">更新</el-button>
            <el-button type="danger" size="small" @click="del(row.id)" v-permission="[2]">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="pageInfo.pageNum"
          :page-size="pageInfo.pageSize"
          :total="pageInfo.total"
          layout="prev, pager, next"
          @current-change="loadTable"
          class="pagination"
      />
    </div>

    <!-- 预览模态框 -->
    <el-dialog v-model="previewVisible" :title="previewTitle" width="60%">
      <img v-if="imgShow" :src="url" class="preview-content" />
      <video v-if="videoShow" :src="url" controls class="preview-content"></video>
    </el-dialog>

    <!-- 编辑模态框 -->
    <el-dialog v-model="editDialogVisible" :title="entity.id ? '编辑文件' : '新增文件'">
      <!-- 添加 rules 和 ref -->
      <el-form ref="formRef" :model="entity" :rules="rules" label-width="100px">
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="entity.name" />
        </el-form-item>
        <el-form-item label="上传时间" prop="time">
          <el-date-picker
              v-model="entity.time"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="文件分类" prop="typeId">
          <el-select v-model="entity.typeId">
            <el-option
                v-for="item in typeObjs"
                :key="item.id"
                :value="item.id"
                :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="fileId">
          <input type="file" ref="fileInput" @change="upload" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="update">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from "@/utils/request.js";


// 响应式数据
//const user = ref(JSON.parse(localStorage.getItem('user')))
const tableData = ref([])
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})
const typeObjs = ref([])
const name = ref('')
const typeId = ref(0)
const entity = reactive({})
const previewTitle = reactive()
const previewVisible = ref(false)
const editDialogVisible = ref(false)
const url = ref('')
const imgShow = ref(false)
const videoShow = ref(false)
const fileInput = ref(null)
//const permission = ref([])
const permission = ref(null)

//校验
const formRef = ref(null)
const rules = reactive({
  name: [
    { required: true, message: '请输入文件名称', trigger: 'blur' }
  ],
  time: [
    { required: true, message: '请选择上传时间', trigger: 'change' }
  ],
  typeId: [
    { required: true, message: '请选择文件分类', trigger: 'change' }
  ],
  fileId: [
    { validator: (rule, value, callback) => {
        if (!entity.id && !entity.fileId) {
          callback(new Error('请上传文件'))
        } else {
          callback()
        }
      }, trigger: 'change' }
  ]
})
// 生命周期钩子
onMounted(async () => {
  await loadTable(1)
  await fetchPermissions()
  await fetchFileTypes()
})

// 方法声明
const loadTable = async (pageNum = 1) => {
  try {
    const res = await request.get(`/fileInfo/page/${name.value || 'all'}/${typeId.value}?pageNum=${pageNum}`)
    console.log("res=="+res)
    console.log("tableData.value=="+res.data.data.list)
    tableData.value = res.data.data.list
    Object.assign(pageInfo, res.data.data)
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const fetchPermissions = async () => {
  try {
    const res = await request.get('/permission/4')
    if (res.data.code === '0') {
      permission.value = res.data.data
    } else {
      permission.value = []
    }
  } catch (error) {
    permission.value = []
    ElMessage.error('权限加载失败')
  }
}

const fetchFileTypes = async () => {
  try {
    const res = await request.get('/typeInfo')
    typeObjs.value = res.data.data
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const viewModal = async (row) => {
  try {
    const res = await request.get(`/fileInfo/${row.id}`)
    url.value = `http://localhost:8888/files/download/${res.data.data.fileId}`
    const fileName = res.data.data.fileName
    console.log("fileName="+fileName)
    if (/\.(png|jpg|jpeg|gif|webp)$/i.test(fileName)) {
      imgShow.value = true
      videoShow.value = false
    } else if (/\.mp4$/i.test(fileName)) {
      imgShow.value = false
      videoShow.value = true
    } else {
      ElMessage.warning('不支持该格式预览')
      return
    }
    previewVisible.value = true
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const add = () => {
  Object.keys(entity).forEach(key => delete entity[key])
  if (fileInput.value) fileInput.value.value = ''
  editDialogVisible.value = true
}

const init = (row) => {
  Object.assign(entity, row)
  editDialogVisible.value = true
}

const upload = async () => {
  const files = fileInput.value.files
  if (!files.length) return

  const formData = new FormData()
  formData.append('file', files[0])

  try {
    const res = await request.post('/files/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    entity.fileId = res.data.data.id
    entity.fileName = res.data.data.originName
    ElMessage.success('文件上传成功')
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const update = async () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return
    }

    try {
      const method = entity.id ? 'put' : 'post'
      await request[method]('/fileInfo', entity)
      ElMessage.success('操作成功')
      editDialogVisible.value = false
      await loadTable(pageInfo.pageNum)
    } catch (error) {
      ElMessage.error(error.message)
    }
  })
}

const del = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该文件？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await request.delete(`/fileInfo/${id}`)
    ElMessage.success('删除成功')
    await loadTable()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message)
    }
  }
}

const downFile = async (id) => {
  try {
    const res = await request.get(`/fileInfo/${id}`)
    const fileId = res.data.data.fileId
    console.log("typeId="+typeId)
    window.open(`http://localhost:8888/files/download/${fileId}`, '_blank');
  } catch (e) {
    console.error('下载失败:', e);
    // 显示用户友好提示
  }
}

</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  background: linear-gradient(to bottom, #26a3de, #057db5);
  color: white;
}

.section-title {
  padding: 20px;
  font-style: italic;
}

.search-bar {
  padding: 20px;
  display: flex;
  gap: 10px;
}

.data-table {
  margin: 20px;
}

.pagination {
  justify-content: center;
  margin: 20px;
}

.preview-content {
  max-width: 100%;
  max-height: 60vh;
  display: block;
  margin: 0 auto;
}
</style>